<?php
namespace plugin\wechat\app\exception;

use Throwable;
use Webman\Http\Request;
use Webman\Http\Response;

/**
 * Class Handler
 * @package Support\Exception
 */
class Handler extends \Webman\Exception\ExceptionHandler
{
    public function render(Request $request, Throwable $exception): Response
    {
        $debug = getenv('APP_DEBUG');
        $code = $exception->getCode();
        if ($request->expectsJson()) {
            $json = ['code' => $code ? $code : 500, 'msg' => $debug ? $exception->getMessage() : 'Server internal error'];
            $debug && $json['traces'] = \explode("\n", (string)$exception);
            return new Response(200, ['Content-Type' => 'application/json'],
                \json_encode($json, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
        }

        return $debug ? new Response(500,[], \nl2br((string)$exception)) : view(config('app.exception_tpl'), ['trace' => \nl2br($exception->getTraceAsString())]);
    }
}
